package com.study.lu.链表;

import com.study.lu.链表.bean.Node;

import static com.study.lu.链表.bean.Node.createNode;

/**
 * 链表反转
 */
public class 链表反转 {

    public static void main(String[] args) {
        String str = "abcdefg";
        Node node = createNode(str);
        printNode(node);
        System.out.println();
        // 循环
          node = recove1(node);
        // 递归
       // node = recove2(node);
        printNode(node);
        System.out.println();
    }

    private static Node recove2(Node curr) {
        if (null == curr || null == curr.next) {
            return curr;
        }
        // 递归后拿到最后一个节点
        Node resNode = recove2(curr.next);
        // 把当前这个节点放在 resNode.next 即 resNode.next == node
        //  curr.next == resNode
        curr.next.next = curr;
        // 然后清空当前节点指向下一个节点
        curr.next = null;
        return resNode;
    }

    private static Node recove1(Node node) {
        // a.next->b.next->c.next->d
        //  temp= b.next   b.next = a
        Node prev = null, curr, next;
        curr = node;
        while (null != curr) {
            // 先存储下一个需要遍历的节点
            next = curr.next;
            // 把当前节点的下一个节点指向上一个节点
            curr.next = prev;
            // 存储反转后的结果
            prev = curr;
            // 取出下一个节点 遍历
            curr = next;
        }

        return prev;

    }

    private static void printNode(Node node) {
        if (null == node) {
            return;
        }
        while (null != node) {
            System.out.print(node.data);
            node = node.next;
            System.out.print("->");
        }
    }

    private static Node recove3(Node curr) {
        if (curr == null || curr.next == null) {
            return curr;
        }
        // 拿到最后一个节点
        Node last = recove3(curr.next);

        // 翻转 eg: 1->2->3 ；1要跟2调换。那么就是2.next=1 1.next=null
        curr.next.next=curr;
        // 1.next=null
        curr.next = null;
        return last;

    }


}

